/*
STL 常用拷贝与替换算法
算法简介
  copy  // 容器指定范围的元素拷贝到另一个容器
  replace  // 容器内指定范围的旧元素替换为新元素
  replace_if  // 体检替换
  swap  // 互换两个容器

copy
  拷贝
  函数原型
    copy(iterator beg, iterator end, iterator dest)

replace
  替换
  函数原型
    replace(iterator beg, iterator end, oldvalue, newvalue);

replace_if
  条件替换
  函数原型
    replace_if(iterator beg, iterator end, _Pred, newvalue);  _Pred 函数或谓词

swap
  互换容器
  函数原型
    swap(container c1, container c2);
*/

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

void print(int v)
{
    cout << v << " ";
}

// copy
void test_copy()
{
    cout << "------------ copy ------------" << endl;
    vector<int> v1 = {1, 2, 3, 4, 5};
    cout << "v1 -> ";
    for_each(v1.begin(), v1.end(), print);
    cout << endl;

    vector<int> v2;
    v2.resize(v1.size());
    copy(++v1.begin(), --v1.end(), v2.begin());
    cout << "v2 -> ";
    for_each(v2.begin(), v2.end(), print); // 2 3 4 0 0
    cout << endl;
}

// replace
void test_replace()
{
    cout << "------------ replace ------------" << endl;
    vector<int> v = {1, 2, 3, 4, 5};
    cout << "v -> ";
    for_each(v.begin(), v.end(), print);
    cout << endl;

    replace(v.begin(), v.end(), 2, 20);
    cout << "2 replace 20 v -> ";
    for_each(v.begin(), v.end(), print);
    cout << endl;
}

// replace_if
class OddNum // 奇数
{
public:
    bool operator()(int val)
    {
        int remainder = val % 2;
        return remainder != 0;
    }
};

void test_replace_if()
{
    cout << "------------ replace_if ------------" << endl;
    vector<int> v = {1, 2, 3, 4, 5};
    cout << "v -> ";
    for_each(v.begin(), v.end(), print);
    cout << endl;

    replace_if(v.begin(), v.end(), OddNum(), 9);
    cout << "replace_if v -> ";
    for_each(v.begin(), v.end(), print);
    cout << endl;
}

// swap
void test_swap()
{
    cout << "------------ swap ------------" << endl;
    vector<int> v1 = {1,2,3};
    cout << "v1 -> ";
    for_each(v1.begin(), v1.end(), print);
    cout << endl;

    vector<int> v2 = {11,21,31, 41, 51};
    cout << "v2 -> ";
    for_each(v2.begin(), v2.end(), print);
    cout << endl;

    cout << "after swap..." << endl;
    swap(v1, v2);

    cout << "v1 -> ";
    for_each(v1.begin(), v1.end(), print);
    cout << endl;

    cout << "v2 -> ";
    for_each(v2.begin(), v2.end(), print);
    cout << endl;
}

int main()
{
    test_copy();
    test_replace();
    test_replace_if();
    test_swap();

    return 0;
}